package com.zhen.aikan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhen.aikan.constant.RedisConstants;
import com.zhen.aikan.entity.User;
import com.zhen.aikan.service.ILoginService;
import com.zhen.aikan.service.IUserService;
import com.zhen.aikan.util.RedisUtils;
import com.zhen.aikan.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LiJiaZhen
 * @date 2023/9/20 14:59
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Map<String, Object> login(UserVo userVo) {
        Map<String, Object> msg = new HashMap<>();
        if(BeanUtil.isEmpty(userVo)){
            msg.put("code",201);
            msg.put("msg","数据非法");
            return msg;
        }
        //用户是否存在
        BaseMapper<User> userBaseMapper = userService.getBaseMapper();
        User user = userBaseMapper.selectOne(new QueryWrapper<User>()
                .eq("user_id", userVo.getId())
                .or()
                .eq("email", userVo.getId()));
        if(BeanUtil.isEmpty(user)){
            msg.put("code",201);
            msg.put("msg","用户不存在");
            return msg;
        }
        //判断密码是否正确
        if(!user.getPassword().equals(userVo.getPassword())){
            msg.put("code",201);
            msg.put("msg","密码错误");
            return msg;
        }
        //将用户保存到redis
        //随机一个token
        String token = UUID.randomUUID().toString(true);
        //去除密码
        user.setPassword("");
        Map<String, Object> userMap = RedisUtils.setUserMap(user,token);
        msg.put("code",200);
        msg.put("msg","登录成功");
        msg.put("token",token);
        msg.put("user",userMap);
        return msg;
    }

    @Override
    public Map<String, Object> logout(String token) {
        Map<String,Object> map = new HashMap<>();
        Boolean delete = stringRedisTemplate.delete(RedisConstants.LOGIN_USER_KEY + token);
        if(delete){
            map.put("code",200);
            map.put("msg","登出成功");
            return map;
        }
        map.put("code",201);
        map.put("msg","登出失败");
        return map;
    }
}
